import 'package:async/async.dart';
import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/member/page/memberAdd.dart';
import 'package:boss/ui/page/member/page/memberDetails.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:boss/ui/widget/search_bar.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:router/annotation.dart';

@RouterConfig(MemberAdministration.pageName)
class MemberAdministration extends StatefulWidget {
  static const pageName = '/memberAdministrationPage';

  @override
  MyMemberAdministration createState() => MyMemberAdministration('会员管理');
}

class MyMemberAdministration extends BaseState<MemberAdministration> {
  String searchWord = '';

  List<dynamic> items = [];
  List<dynamic> memberArr = [];

  int page = 1;
  int rows = 10;
  int _total = 0;

  //今日新增
  int todayAdd = 0;

  MyMemberAdministration(String pageName) : super(pageName);

  @override
  void initState() {
    super.initState();
    memberHeadFun();
    memberListFun();
  }

  memberHeadFun() async {
    var res = await api.memberHead();
    if (res.successful()) {
      if (res.data != null) {
        todayAdd = res.data["todayNum"];
        setState(() {});
      }
    } else {
      toast(res.msg);
    }
  }

  memberListFun({bool myBool, bool load}) async {
    try {
      if (myBool == null || myBool == true) {
        showLoadingToast();
      }

      var res = await api.searchMember(
        input: searchWord,
        rows: rows,
        page: page,
      );

      if (res.successful()) {
        if (res.data != null) {
          if (load == true) {
            memberArr.addAll(res.data["items"]);
          } else {
            memberArr = res.data["items"];
          }

          _total = res.data["total"];
          items = res.data["items"];
          setState(() {});
//            return Result.value(res['data']["items"]);
        }
      } else {
        toast(res.msg);
        return Result.error(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  //iamge 图文
  imageTitle() {
    return Container(
      child: Stack(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(
              30.w,
            ),
            child: BaseImage(
              '${"assets/image/memberAdministration.png"}',
              width: double.infinity,
            ),
          ),
          Positioned(
            top: 50.w,
            left: 0,
            right: 0,
            child: Column(
              children: <Widget>[
                Text(
                  "今日新增",
                  style: TextStyleConstant().white_32,
                ),
                Padding(
                  padding: EdgeInsets.only(
                    top: 30.w,
                    bottom: 24.w,
                  ),
                  child: Text(
                    "$todayAdd",
                    style: TextStyleConstant().normal_5_70,
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(
                    left: 12.w,
                    right: 12.w,
                    top: 12.w,
                    bottom: 12.w,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(24),
                  ),
                  child: Text(
                    "${"累计会员：${_total == null ? '--' : _total}人"}",
                    textAlign: TextAlign.center,
                    style: TextStyleConstant().blue_26,
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  //搜索框
  searchElement() {
    return Padding(
      padding: EdgeInsets.only(
        left: 28.w,
        right: 28.w,
        top: 0.w,
        bottom: 10.w,
      ),
      child: SearchBar(
        hintText: '输入手机号',
        onChanged: (value) {
          setState(() {
            searchWord = value;
            page = 1;
            memberListFun(myBool: false);
          });
        },
      ),
    );
  }

  Future<Result<List<dynamic>>> loadMoreOrderList() async {
    page += 1;

    await memberListFun(myBool: false, load: true);
    return Result.value(items);
  }

  Future<Result<List<dynamic>>> refreshTask() async {
    page = 1;
    await memberListFun(myBool: false);
    return Result.value(items);
  }

  Future<Result<List<dynamic>>> _loadTask() async {
    return await loadMoreOrderList();
  }

  Future<Result<List<dynamic>>> _refreshTask() async {
    return await refreshTask();
  }

  //list 内容
  listContent() {
    //时间格式转为/间隔
    timeFormat(Time) {
      if (Time == null) {
        return '';
      }
      if (Time.length < 10) {
        return "";
      }

      var myTime = Time.toString().substring(0, 10);

      String newTime = myTime.replaceAll("-", "/");
      return newTime;
    }

    return Expanded(
      child: LoaderPullRefresh<dynamic>(
          key: Key("LoaderPullRefreshFun"),
          loadTask: _loadTask,
          refreshTask: _refreshTask,
          builder: (context) {
            return SingleChildScrollView(
              child: Column(
                children: <Widget>[
//                  memberArr.length==0?Container(
//                    margin: EdgeInsets.only(
//
//
//                      top:200.w,
//
//                    ),
//                    child:Text("暂无数据",
//                      style:TextStyleConstant().gray_28_deep,
//                    ),
//                  ):Container(),

                  Column(
                    children: memberArr
                        .map<Widget>((item) => InkWell(
                              onTap: () async {
                                await Navigator.pushNamed(context, MemberDetails.pageName, arguments: {"data": item});
                              },
                              child: Container(
//               height:110.w,
                                child: Padding(
                                  padding: EdgeInsets.only(
                                    left: 28.w,
                                    right: 28.w,
                                  ),
                                  child: Container(
                                    child: Column(
                                      children: <Widget>[
                                        Stack(
                                          children: <Widget>[
                                            item["status"] == 1
                                                ? Positioned(
                                                    left: 6.w,
                                                    top: 15.w,
                                                    child: BaseImage(
                                                      'assets/image/frozen.png',
                                                      width: 60.w,
                                                      height: 60.w,
                                                    ),
                                                  )
                                                : Container(),
                                            Padding(
                                              padding: EdgeInsets.only(
                                                top: 32.w,
                                                bottom: 32.w,
                                              ),
                                              child: Row(
                                                children: <Widget>[
                                                  Container(
                                                    width: 200.w,
                                                    child: Text(
                                                      "${item["phoneNum"] == null ? '--' : item["phoneNum"]}",
                                                      style: TextStyleConstant().normal_1_28,
                                                    ),
                                                  ),
                                                  Expanded(
                                                    child: Container(
                                                      child: Text(
                                                        "${item["name"] == null ? '' : (item["name"] == '' ? '' : item["name"])}",
                                                        overflow: TextOverflow.ellipsis,
                                                        style: TextStyleConstant().normal_1_28,
                                                      ),
                                                    ),
                                                  ),
                                                  Container(
                                                    width: 280.w,
                                                    child: Row(
                                                      children: <Widget>[
                                                        Text(
                                                          " ${timeFormat(item["finalConsumeTime"]) == '' ? '' : '最后消费：'}",
                                                          style: TextStyleConstant().gray_23,
                                                        ),
//                                            Text("${item["ctime"]==null?'--':(item["ctime"]).toString().substring(0,10)}",
//                                              style: TextStyleConstant().normal_1_24,
//                                            ),
                                                        Text(
                                                          "${item["finalConsumeTime"] == null ? '' : (timeFormat(item["finalConsumeTime"]))}",
                                                          style: TextStyleConstant().normal_1_24,
                                                        ),
                                                      ],
                                                    ),
                                                  ),
                                                  Container(
                                                    width: 90.w,
                                                    child: Text(
                                                      "${item["memberRank"] == null ? '--' : item["memberRank"]["rankName"]}", //普通
                                                      overflow: TextOverflow.ellipsis,
                                                      style: TextStyleConstant().normal_1_28,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                        Container(
                                          height: 1,
                                          color: Color.fromRGBO(247, 247, 247, 1),
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ))
                        .toList(),
                  ),
                  SizedBox(
                    height: 30.w,
                  ),
                ],
              ),
            );
          }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CenterTitleAppBar(
        title: '会员管理',
        actions: <Widget>[
          LabelButton(
            title: '新增',
            onTap: () {
              Future.delayed(Duration(milliseconds: 0), () async {
                var result = await Navigator.pushNamed(context, MemberAdd.pageName);

                if (result != null) {
                  memberHeadFun();

                  page = 1;
                  memberListFun(myBool: false);
                }
              });
            },
          ),
        ],
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            imageTitle(),
            searchElement(),
            listContent(),
          ],
        ),
      ),
    );
  }
}
